package com.loongtech.bi.action.system;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Session;

/**
 * 系统用户注册
 * 
 * @author xckuang
 * @date 2014-10-06
 */
@Controller("sysUserRegisterAction")
@Scope("view")
public class SysUserRegisterAction implements Serializable {
	private static final long serialVersionUID = 1L;
	@Autowired
	private Session session;
	@Autowired
	private SysUserManager sysUserManager;
	@Autowired
	private SysLogManager sysLogManager;
	private EntitySysUser user;

	@Autowired
	public void init() {
		setUser(new EntitySysUser());
	}

	public void register() {
		FacesContext context = FacesContext.getCurrentInstance();

		// 判断参数
		String username = user.getUsername();
		if (null == username || username.isEmpty()) {
			context.addMessage(null, new FacesMessage("注册用户失败", "用户名为空!"));
			return;
		}
		String password = user.getPassword();
		if (null == password || password.isEmpty()) {
			context.addMessage(null, new FacesMessage("注册用户失败", "密码为空!"));
			return;
		}
		// 判断用户username是否已经被注册
		if (null != sysUserManager.getBy(EntitySysUser.K.username, username)) {
			context.addMessage(null, new FacesMessage("注册用户失败", "用户名已注册!"));
			return;
		}
		// 注册用户
		try {
			Integer userId = sysUserManager.register(user);
			if (null != userId && userId > 0) {
				context.addMessage(null, new FacesMessage("注册用户成功", "userId=" + userId));
				sysLogManager.addLog(session.getUserName(), username+"用户注册成功");
				setUser(new EntitySysUser());
				return;
			} else {
				context.addMessage(null, new FacesMessage("注册用户失败", "注册失败!"));
				return;
			}
		} catch (Exception ex) {
			context.addMessage(null, new FacesMessage("注册用户失败", "注册时发生异常!"));
			return;
		}
	}

	public EntitySysUser getUser() {
		return user;
	}

	public void setUser(EntitySysUser user) {
		this.user = user;
	}
}
